﻿using System;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Text;
using System.Web.UI;
using AMS.Inventory.Entities;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Helper;
using VitCode.Castle.Management;
using VitCode.Web.UI;


namespace AMSInventoryWeb.BaseData
{
    public partial class ObjList : Page
    {
        private readonly CreateControlHelper m_CreateCtlHlp = new CreateControlHelper();
        private PageBuilder m_PageBuilder;
        readonly PermissionManager psManager = new PermissionManager();


        private UserDataSourceBuilder DataSourceBuilder
        {
            get { return (UserDataSourceBuilder)Session["DataSourceBuilder"]; }
            set { Session["DataSourceBuilder"] = value; }
        }

        public string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\BaseDataSet.xml"; }
        }

        private string ClassName
        {
            get { return m_CreateCtlHlp.ReturnQueryStringValue("ClassName",this); }
        }

        private string TypeName
        {
            get { return m_CreateCtlHlp.ReturnQueryStringValue("TypeName",this); }
        }

        private string MenuId
        {
            get { return m_CreateCtlHlp.ReturnQueryStringValue("MenuId", this); }
        }

        private string QueryCondition
        {
            get
            {
                
                if (ViewState["QueryCondition"] != null)
                    return ViewState["QueryCondition"].ToString();
                else
                    return "";
            }
            set { ViewState["QueryCondition"] = value; }
        }


        protected override void OnInit(EventArgs e)
        {
            if (m_PageBuilder == null)
                m_PageBuilder = new PageBuilder(this,SettingXmlPath);
            NavigateCtl1.SettingXmlPath = SettingXmlPath;
            if (TypeName.Length > 0)
                m_PageBuilder.SetPgListAttribute(pgList, ClassName, TypeName);
            else
                m_PageBuilder.SetPgListAttribute(pgList, ClassName);
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            

            pgList.DataSourceBuilderDelegate = new PaginationGrid.GridDataSourceBuilderDelegate(BindPgList);
            if (!IsPostBack)
            {
               
                PagePermissionHelper.CheckIsLoginToDefault(this);
                m_CreateCtlHlp.SetDdlCondition(pgList,ddlCondition);
                btnAdd.Enabled = psManager.CheckPageIsCanAdd(this, true);
            }
        }


        private PaginationGridDataSourceBuilder BindPgList()
        {
            string sql = m_PageBuilder.GetPgListSqlValue(ClassName, TypeName);
            sql = sql.Replace("\r\n", " ").Replace("\t", " ");
            if (sql.IndexOf("{0}") > -1)
                sql = sql.Replace("{0}", TypeName);
            sql += " " + QueryCondition;
            DataSourceBuilder = new UserDataSourceBuilder(sql, pgList);
            return DataSourceBuilder;
        }

        private void ListBind()
        {
            pgList.BindGrid();
            bool isCanDelete = (DataSourceBuilder.PrimaryKeys != null && DataSourceBuilder.PrimaryKeys.Count > 0);
            btnRealDelete.Enabled = isCanDelete;
            btnRealDelete.Enabled = psManager.CheckPageIsCanDelete(this,true);
        }


        protected void pgList_OnGridItemSelect(object sender, PaginationGridItemSelectArgs e)
        {
            Response.Redirect("ObjEdit.aspx?MenuId="+MenuId+"&ClassName=" + ClassName + "&TypeName=" + TypeName + "&" +
                              m_PageBuilder.GetPageKeyField(ClassName) + "=" +
                              e.SelectedDataKeyValue,false);
        }

        protected void btnRealDelete_Click(object sender, EventArgs e)
        {
            string strDelVal = pgList.GetSelectedItem(1);
            CreateControlHelper cch = new CreateControlHelper();
            Type classType = m_PageBuilder.m_LoadHelper.GetClassTypeByClassNodeName(ClassName);
            string proName = m_PageBuilder.GetPageKeyField(ClassName);
            PropertyInfo pi = classType.GetProperty(proName);
            var acc = new BaseDataAccess();
            acc.BeginTransaction();
            try
            {
                StringCollection sc = acc.DeleteReErrMsg(false, strDelVal, pi.PropertyType, classType);
                
                if (sc.Count == 0)
                {
                    if (ClassName == typeof(PlanInfo).Name)
                    {
                         
                        if(!CheckIsCanDelete(strDelVal))
                        {
                            ClientScript.RegisterStartupScript(ClientScript.GetType(), "100", "<script language='javascript'>alert('进行中或已结束的盘点计划不能删除！')</script>");
                            return;
                            
                        }
                    }
                        acc.DeleteObjectsByKeyValues(typeof (InventoryInfo).Name, "PlanId", strDelVal);
                    acc.Commit();
                    Alert.WebMessageBox(Page,"所选彻底删除成功");
                }
                else
                {
                    var sb = new StringBuilder();
                    sb.Append("部分数据不能删除,原因如下:\r\n");
                    for (int i = 0; i < sc.Count; i++)
                    {
                        string str = sc[i];
                        cch.SetDeleteErrMsgEachClassMemo(ref str);
                        sb.Append(str + "\r\n");
                    }
                    acc.RollBack();
                    Alert.WebMessageBox(Page,sb.ToString());
                }
                ListBind();
            }
            catch
            {
                acc.RollBack();
                throw;
            }
            finally
            {
                acc.CloseSession();
            }
        }

        private bool CheckIsCanDelete(string strDelVal)
        {
            var acc = new BaseDataAccess();
            var planIdList = strDelVal.Split(',');
            var sb = new StringBuilder();
            for (var i = 0; i < planIdList.Length; i++)
            {
                if (planIdList[i].Length > 0 && planIdList[i].Length == 36)
                {
                    var objList = acc.GetObjectList(new PlanInfo().GetType().Name, "Id", planIdList[i]);
                    if (objList != null && objList.Count > 0)
                    {
                        var currentPlanInfo = (PlanInfo)objList[0];
                        var planState = currentPlanInfo.State;
                        if (planState == "Finish" || planState == "Doing")
                        {
                            sb.Append("进行中或已结束的盘点计划不能删除！");
                            return false;
                        }
                    }
                }
            }
            return true;
         
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string editUrl = "ObjEdit.aspx?MenuId=" + MenuId + "&ClassName=" + ClassName;
            if (TypeName.Length > 0)
                editUrl += "&TypeName=" + TypeName;
            editUrl += "&Operate=Add";
            Response.Redirect(Server.UrlPathEncode(editUrl));
        }

        protected void ConditionSelector1_SelectCondition(SelectConditionEventArgs e)
        {
            QueryCondition = null;
            if (ConditionSelector1.SelectedConditionString.Length > 0)
                QueryCondition = " where " + ConditionSelector1.SelectedConditionString;
            ListBind();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            QueryCondition = QueryHelper.GetQueryCondition(ddlCondition.SelectedValue, txtValue.Text, rbtAmount.Checked);
            ListBind();
        }
    }
}